﻿using System;
using System.Diagnostics;
using System.Linq;
using ServiceStack.Text;

namespace Mnk.Merger.Code.Common
{
    class ProcessExecutor : IProcessExecutor
    {
        public ProcessResult Execute(string command, string workingDirectory = "")
        {
            using (var p = CreateProcess(command, workingDirectory))
            {
                var result = new ProcessResult
                {
                    StandardOutputLines = p.StandardOutput.ReadLines().ToArray(),
                    StandardError = p.StandardError.ReadToEnd()
                };
                p.WaitForExit();
                Verify(p, result);
                return result;
            }
        }

        private static Process CreateProcess(string command, string workingDirectory)
        {
            return Process.Start(new ProcessStartInfo
            {
                FileName = "cmd",
                Arguments = "/c " + command,
                WorkingDirectory = workingDirectory,
                CreateNoWindow = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true,

                UseShellExecute = false
            });
        }

        private static void Verify(Process p, ProcessResult result)
        {
            if (p.ExitCode == 0) return;
            throw new Exception(
                "Can't execute command: " + p.StartInfo.Arguments 
                + ", exitCode=" + p.ExitCode 
                + Environment.NewLine + "Output: " + Environment.NewLine
                + result.StandardOutput + Environment.NewLine + result.StandardError);
        }
    }
}